package com.ghp.common.utils;

import java.security.SecureRandom;
import java.util.Base64;

/**
 * 密钥生成工具类
 */
public class KeyGeneratorUtils {

  private KeyGeneratorUtils(){}

  private static final int DEFAULT_ACCESS_KEY_LENGTH = 16;
  private static final int DEFAULT_SECRET_KEY_LENGTH = 32;

  /**
   * 生成 Access Key，采用默认长度16
   * @return
   */
  public static String generateAccessKey() {
    SecureRandom random = new SecureRandom();
    byte[] keyBytes = new byte[DEFAULT_ACCESS_KEY_LENGTH];
    random.nextBytes(keyBytes);
    return encodeBase64URLSafe(keyBytes);
  }

  /**
   * 生成 Secret Key，采用默认长度32
   * @return
   */
  public static String generateSecretKey() {
    SecureRandom random = new SecureRandom();
    byte[] keyBytes = new byte[DEFAULT_SECRET_KEY_LENGTH];
    random.nextBytes(keyBytes);
    return encodeBase64URLSafe(keyBytes);
  }

  /**
   * 生成 Access Key
   * @param length
   * @return
   */
  public static String generateAccessKey(int length) {
    SecureRandom random = new SecureRandom();
    byte[] keyBytes = new byte[length];
    random.nextBytes(keyBytes);
    return encodeBase64URLSafe(keyBytes);
  }

  /**
   * 生成 Secret Key
   * @param length
   * @return
   */
  public static String generateSecretKey(int length) {
    SecureRandom random = new SecureRandom();
    byte[] keyBytes = new byte[length];
    random.nextBytes(keyBytes);
    return encodeBase64URLSafe(keyBytes);
  }

  /**
   * 采用URL安全的Base64编码
   * @param bytes
   * @return
   */
  public static String encodeBase64URLSafe(byte[] bytes) {
    return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
  }


  /**
   * 用于测试，无实际作用，可删除
   */
  public static void main(String[] args) {
    String accessKey = generateAccessKey();
    String secretKey = generateSecretKey();

    System.out.println("Access Key: " + accessKey);
    System.out.println("Secret Key: " + secretKey);
  }
}